# -*- coding:utf-8 -*-
# Author: MaXiaoLong
# Data: 2020/10/27 17:47
import os
import urllib2
import urllib


def create_nacos_namespace(url, nsName, nsID, nsDesc):
    conn = "http://%s/nacos/v1/console/namespaces" % url

    payload = {"namespaceName": nsName, "namespaceDes": nsDesc, "customNamespaceId": nsID}

    # headers = {'content-type': "application/x-www-form-urlencoded"}

    req = urllib2.Request(url=conn)
    req.add_header('content-type', "application/x-www-form-urlencoded")

    response = urllib2.urlopen(req, urllib.urlencode(payload))

    print("create namespace %s success, resp code: %s" % (nsName, response.getcode()))

    return response.getcode()


def uploadConfigTONacos(url, cf_dict):
    if not cf_dict:
        print("配置字典为空")
        return

    path = "http://%s/nacos/v1/cs/configs" % url

    # headers = {'content-type': "multipart/form-data; boundary=---011000010111000001101001"}

    nsName = cf_dict.get("namespacename")
    nsId = cf_dict.get("namespaceid")
    dataId = cf_dict.get("dataid")
    group = cf_dict.get("group")
    filePath = cf_dict.get("localfile")

    with open(filePath, "r") as f:
        content = f.read()

    payload = {"dataId": dataId, "tenant": nsId, "group": group, "content": content, "type": "xml", "namespaceId": nsId}

    req = urllib2.Request(url=path)
    req.add_header('content-type', "multipart/form-data")
    response = urllib2.urlopen(path, data=urllib.urlencode(payload))

    print("success write config xml file to %s %s %s,response code: %s" % (nsName, group, dataId, response.getcode()))
    return response.getcode()


if __name__ == '__main__':
    url = "{{ hostvars[groups.nacos[0]].ansible_ssh_host }}:{{ nacos.port }}"
    confPath = "{{ br.root }}/conf"
    filePath = confPath + "/{{ nacos.dir }}"
    ns_list = [
        {"namespacename": "BONREE_GLOBAL", "namespaceid": "b1751c5c-13d9-49c0-a6b1-8487f9f46f96",
         "dataid": "GLOBAL", "group": "CONFIG_GLOBAL", "localfile": os.path.join(confPath, "{{ nacos.global_file }}")},
    ]

    for ns in ns_list:
        nsDesc = "create namespace %s" % ns
        nsName, nsID = ns.get("namespacename"), ns.get("namespaceid")
        create_nacos_namespace(url, nsName, nsID, nsDesc)

        uploadConfigTONacos(url, ns)
